package com.xiaomi.shwx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomi.shwx.common.enums.WorkOrderEvents;
import com.xiaomi.shwx.common.enums.WorkOrderStatus;
import com.xiaomi.shwx.common.exception.BaseException;
import com.xiaomi.shwx.common.result.ResultCodeEnum;
import com.xiaomi.shwx.common.statemachine.WorkOrderProcessor;
import com.xiaomi.shwx.common.util.Constant;
import com.xiaomi.shwx.entity.dto.MaterialsDTO;
import com.xiaomi.shwx.entity.dto.WorkOrderDTO;
import com.xiaomi.shwx.entity.pojo.Material;
import com.xiaomi.shwx.entity.pojo.WorkOrder;
import com.xiaomi.shwx.entity.request.WorkOrderSearchRequest;
import com.xiaomi.shwx.entity.vo.WorkOrderVO;
import com.xiaomi.shwx.mapper.MaterialMapper;
import com.xiaomi.shwx.mapper.WorkOrderMapper;
import com.xiaomi.shwx.service.WorkOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 工单 服务实现类
 * </p>
 *
 * @author Lei
 * @since 2024-05-15
 */
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrder> implements WorkOrderService {

    @Resource
    private MaterialMapper materialMapper;

    @Resource
    private WorkOrderMapper workOrderMapper;

    @Resource
    private WorkOrderProcessor workOrderProcessor;

    @Override
    public void applyMaterials(MaterialsDTO materialsDTO) {
        Material material = materialMapper.selectById(materialsDTO.getId());
        if (Objects.isNull(material)) {
            throw new BaseException("申请失败,材料不足", ResultCodeEnum.FAIL.getCode());
        }
        WorkOrder workOrder = workOrderMapper.selectById(materialsDTO.getWork_order_id());
        workOrder.setMaterialId(materialsDTO.getId());
        workOrder.setMaterialNum(materialsDTO.getCount());
        workOrder.setStatus(WorkOrderStatus.RECHECK.getStatus());
        // 费用计算，物料的成本费用*120% + 工程师手工费（固定为50元）
        int totalPrice = (int) (material.getPrice() * materialsDTO.getCount() * 1.2 + 50);
        workOrder.setPrice(totalPrice);
        workOrderMapper.updateById(workOrder);
    }

    @Override
    public List<WorkOrderVO> listOrder(WorkOrderSearchRequest request) {
        List<WorkOrderVO> res = new ArrayList<>();
        if (request.getFlag().equals(Constant.CLIENT_FLAG) || request.getFlag().equals(Constant.ADMIN_FLAG)) {
            res = workOrderMapper.getClientOrderList(request.getId());
        } else if (request.getFlag().equals(Constant.ENGINEER_FLAG)) {
            res = workOrderMapper.getEngineerOrderList(request.getId());
        }
        if (res.isEmpty()) {
            throw new BaseException("未查询到工单", ResultCodeEnum.FAIL.getCode());
        }
        return res;
    }

    @Override
    public List<WorkOrderVO> listInitialOrder() {
        return workOrderMapper.getInitialOrderList();
    }

    @Override
    public WorkOrderVO addOrder(WorkOrder order) {
        WorkOrderVO response = new WorkOrderVO();
        if (workOrderMapper.insert(order) == 1) {
            BeanUtils.copyProperties(order, response);
            return response;
        }
        return response;
    }

    @Override
    public String createOrder(WorkOrderDTO dto) {
        WorkOrder workOrder = new WorkOrder();
        BeanUtils.copyProperties(dto, workOrder);
        workOrder
                .setStatus(WorkOrderStatus.CREATE.getStatus())
                .setCreateTime(new Date());
        if (save(workOrder)) {
            return WorkOrderEvents.CREATE_SUCCESS.getDescription();
        } else {
            return WorkOrderEvents.CREATE_FAILED.getDescription();
        }
    }

    @Override
    public List<WorkOrderVO> getOrdersByUserId(String userId) {
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clientId", userId);
        List<WorkOrder> list = list(queryWrapper);
        List<WorkOrderVO> result = new ArrayList<>();
        for (WorkOrder workOrder : list) {
            WorkOrderVO vo = new WorkOrderVO();
            BeanUtils.copyProperties(vo, workOrder);
            result.add(vo);
        }
        return result;
    }

    @Override
    public WorkOrderVO userGetOrderById(String workorderId) {
        WorkOrder byId = getById(workorderId);
        WorkOrderVO vo = new WorkOrderVO();
        BeanUtils.copyProperties(vo, byId);
        return vo;
    }

    @Override
    public WorkOrderVO updateOrder(WorkOrder order) {
        int updateRes = workOrderMapper.updateById(order);
        WorkOrderVO res = new WorkOrderVO();
        if (updateRes > 0) {
            BeanUtils.copyProperties(order, res);
            return res;
        }
        throw new BaseException("更新失败", ResultCodeEnum.FAIL.getCode());
    }

    @Override
    public WorkOrderVO payOrder(WorkOrder order) {
        WorkOrder data = workOrderMapper.selectById(order);
        WorkOrderVO res = new WorkOrderVO();
        if (data.getStatus().equals(WorkOrderStatus.UNPAID.getStatus())) {
            data.setStatus(WorkOrderStatus.PAID.getStatus());
            workOrderMapper.updateById(data);
            BeanUtils.copyProperties(data, res);
        }
        return res;
    }

    @Override
    public WorkOrderVO confirmOrder(WorkOrder order) {
        WorkOrder data = workOrderMapper.selectById(order);
        WorkOrderVO res = new WorkOrderVO();
        if (data.getStatus().equals(WorkOrderStatus.BE_CONFIRM.getStatus())) {
            data.setStatus(WorkOrderStatus.CONFIRM.getStatus());
            workOrderMapper.updateById(data);
            BeanUtils.copyProperties(data, res);
        }
        return res;
    }

    @Override
    public WorkOrderVO recheckDone(WorkOrder order) {
        WorkOrder data = workOrderMapper.selectById(order);
        WorkOrderVO res = new WorkOrderVO();
        if (data.getStatus().equals(WorkOrderStatus.RECHECK.getStatus())) {
            data.setStatus(WorkOrderStatus.UNPAID.getStatus());
            workOrderMapper.updateById(data);
            BeanUtils.copyProperties(data, res);
        }
        return res;
    }

    @Override
    public String cancelOrder(String workorderId) {
        WorkOrder byId = getById(Integer.parseInt(workorderId));
        if (Objects.isNull(byId)) {
            return WorkOrderEvents.CANCEL_FAILED.getDescription() + "，工单不存在";
        }
        byId.setStatus(WorkOrderStatus.CANCEL.getStatus());
        UpdateWrapper<WorkOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", workorderId);
        updateWrapper.set("status", WorkOrderStatus.CANCEL.getStatus());
        boolean update = update(byId, updateWrapper);
        if (update) {
            return WorkOrderEvents.CANCEL_SUCCESS.getDescription();
        } else {
            return WorkOrderEvents.CANCEL_FAILED.getDescription();
        }
    }
}

